package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 微网
 * 产品编码 sprdid
 * 验证码产品编码：1012818
 * 通知产品编码：1012808
 * 营销产品编码：1012812
 */
public class SmsApiWEIWANGv3 extends GateWayHttpAbstract
{

    public SmsApiWEIWANGv3(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        Map<String,Object> params = Maps.newHashMap();
        try{
            params.put("sname", paramsMaps.get("sname"));
            params.put("spwd", paramsMaps.get("spwd"));
            params.put("scorpid", "");
            params.put("sprdid", paramsMaps.get("sprdid"));

            params.put("sdst", mt.getPhone());
            String content = URLEncoder.encode(mt.getSmsContent(),"utf-8");
            params.put("smsg", content);
        }
        catch (UnsupportedEncodingException e)
        {
            logger.error("网关:{}, 响应:{}", this.gateWayID, e);
        }

        String json =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/submitdata/service.asmx/g_Submit", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), json);
        
        List<SMSSRMessage> resultList = Lists.newArrayList();
        
        SMSSRMessage message = initGatewayResultMessage(json, mt, "State");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
        
        if(StringUtils.equals(message.getResult(), "F10199")) {
            Document doc;
            try {
                doc = DocumentHelper.parseText(json);
                Element root = doc.getRootElement();
                resultCode = String.valueOf(root.element("State").getStringValue());
                resultMessage = String.valueOf(root.element("MsgID").getStringValue());
                if(StringUtils.equals(resultCode, "0")) {
                    taskid = String.valueOf(root.element("MsgID").getStringValue());
                }
                message.setMsgkey(mt.getPhone());
                setGatewayResultCode(message, taskid, resultCode, resultMessage, "0");
                resultList.add(message);
            } catch(DocumentException e) {
                logger.error("网关:{},号码：{}, 响应:{}", this.gateWayID,mt.getPhone(), e);
                e.printStackTrace();
            }
        }

        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        logger.info("{}网关推送状态报告:{}", gateWayID, text);

        	if(StringUtils.isNotBlank(text)) {
                Map<String, String> map = Splitter.on("&")
                        .withKeyValueSeparator("=")
                        .split(text);
                SMSRTMessage smsRtMessage = initSmsRtMessage(map.get("MsgID"),map.get("MobilePhone"),map.get("MobilePhone"),
                        map.get("SendState"), "True");
                rtList.add(smsRtMessage);
        	}
        return new SmsHttpMsgResponse("1");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
    	logger.info("{}网关推送用户上行:{}", gateWayID, text);
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("1");
        Map<String, String> map = Splitter.on("&")
            .withKeyValueSeparator("=")
            .split(text);
        SMSMOMessage sMSMOMessage = new SMSMOMessage();
        sMSMOMessage.setGateWayID(gateWayID);
        sMSMOMessage.setMsgContent(map.get("Up_UserMsg"));
        sMSMOMessage.setMsgid(map.get("MsgId"));
        sMSMOMessage.setPhone(map.get("Up_UserTel "));
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
        sMSMOMessage.setUuid(UUID.randomUUID().toString());
        moList.add(sMSMOMessage);
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        return null;
    }

    @Override
    public String queryDeliver(String jsonText) {
        return null;
    }
    
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        params.put("sname",paramsMaps.get("sname"));
        params.put("spwd",paramsMaps.get("spwd"));
        params.put("scorpid","");
        params.put("sprdid",paramsMaps.get("sprdid"));
        String apiUrl = paramsMaps.get("apiUrl");
        String result =  HttpRequest.sendPost(apiUrl + "/submitdata/service.asmx/Sm_GetRemain", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        logger.info("余额查询网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);
        Document doc;
        try {
            doc = DocumentHelper.parseText(result);
            Element root = doc.getRootElement();
            if (StringUtils.equals("0",root.element("State").getStringValue())) {
                return  "余额：" + root.element("Remain").getStringValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "余额查询失败";
    }
    
    public static void main(String[] args)
    {
    /*	SmsApiZHAOYONGSMS api = new SmsApiZHAOYONGSMS("JIESMS", "{\"account\":\"lihua\",\"password\":\"llh@9988\",\"longSms\":\"\",\"apiUrl\":\"http://www.88dx.cn\",\"reportSecTime\":\"5\", \"deliverSecTime\":\"5\"}");
    	SMSMTMessage mt = new SMSMTMessage();
    	mt.setPhone("18268846802");
    	mt.setSmsContent("【千橡科技】验证码：123456，10分钟内有效，如非本人操作，请忽略！");
    	List<SMSSRMessage> list = api.doSend(mt);
    	System.out.println(JSON.toJSONString(list));*/
//        String params = "{\"userid\":\"975\",\"account\":\"yhkjjr\",\"password\":\"yhkjjr@2018\",\"apiUrl\":\"https://sms.xinxiguanjia.com/sms.aspx/\"}";
        String params = "{\"sname\":\"dlwujie\",\"spwd\":\"dlwujie00\",\"sprdid\":\"1012818\",\"apiUrl\":\"http://cf.51welink.com\"}";
        SmsApiWEIWANGv3 api = new SmsApiWEIWANGv3("ZY",params);
//        String balance = api.balance();
//        System.out.println("balance=" + balance);
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("15905848777");
        message.setSmsContent("【千橡科技】测试");
        api.doSend(message);
//        System.out.println(balance);
    }
    
}